package com.szl.group.component;

import io.minio.MinioClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description :
 * @Author : shenxl
 * @Date: 2020-11-13 11:24
 */
@Component
@Slf4j
public class FileUploader {


    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;


    @SneakyThrows
    public void upload(MultipartFile file) {

        //创建一个MinIO的Java客户端
        MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
       /* boolean isExist = minioClient.bucketExists(BUCKET_NAME);
        if (isExist) {
            log.info("存储桶已经存在！");
        } else {
            //创建存储桶并设置只读权限
            minioClient.makeBucket(BUCKET_NAME);
            minioClient.setBucketPolicy(BUCKET_NAME, "*.*", PolicyType.READ_ONLY);
        }*/
        String filename = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        // 设置存储对象名称
        String objectName = sdf.format(new Date()) + "/" + filename;

        // 使用putObject上传一个文件到存储桶中
        minioClient.putObject(BUCKET_NAME, objectName, file.getInputStream(), file.getContentType());

        log.info("文件上传成功!");
    }


    @SneakyThrows
    public void delete(String objectName) {

        MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
        minioClient.removeObject(BUCKET_NAME, objectName);

    }
}
